package com.alibaba.citrus.cr.order.open.api.facade.service.calculate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yifei
 * @since 2024/1/27
 */
@Component
public class TransferCalculateHandlerFactory implements ApplicationContextAware {

    private static final Map<String, TransferCalculateQuantityHandler> map = new ConcurrentHashMap<>(3);

    private static ApplicationContext applicationContext;

    public TransferCalculateQuantityHandler getTransferCalculateHandler(String transferType) {
        if (StringUtils.isBlank(transferType)) {
            return null;
        }
        if (map.containsKey(transferType)) {
            return map.get(transferType);
        }
        Map<String, TransferCalculateQuantityHandler> beansOfType = applicationContext.getBeansOfType(TransferCalculateQuantityHandler.class);
        TransferCalculateQuantityHandler handler = beansOfType.values().stream().filter(p -> StringUtils.equals(transferType, p.getTransferType(transferType)))
                .findFirst().orElse(null);
        if (handler == null) {
            return null;
        }
        map.put(transferType, handler);
        return handler;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        TransferCalculateHandlerFactory.applicationContext = applicationContext;
    }
}
